<template>
  <el-container>
    <el-aside width="258px">
      <side_tree :data="treeData" :type="'userGroup'" :default="groupItem.userGroupId" :typeName="'用户组管理'" v-on:childtofather="childtofather"
      />
    </el-aside>
    <el-main>
      <el-col :span="24" class="flex flex-justify clear" style="border-bottom: 1px solid #eee;padding-bottom: 10px">
        <!--名称-->
        <h1>{{groupItem.userGroupName}}</h1>
        <!--按钮-->
        <el-col :span="18" class="flex flex-right">
          <!--按钮-->
          <el-col :span="18" class="flex flex-right">
            <el-button size="small" v-if="roleIdList.includes(10)" type="warning" @click="openModal('userGroup')" style="margin-right:20px">
              <i class="fa fa-plus"></i> 创建用户组</el-button>
            <el-button size="small" v-if="roleIdList.includes(11)" @click="chosen('edit')" :disabled="!isUpdate" type="info">
              <i class="fa fa-edit"></i> 修改
            </el-button>
            <el-button v-if="roleIdList.includes(12)" size="small" type="danger" @click="del">
              <i class="fa fa-trash-o"></i>
              删除</el-button>
          </el-col>
        </el-col>
      </el-col>

      <!--部门信息 表单-->
      <el-form size="small" class="from-box" ref="groupItem" :rules="groupRules" :model="groupItem" label-width="80px">
        <el-col :span="24">
          <el-col :span="6">
            <el-form-item label="用户组名" prop="userGroupName">
              <el-input :readonly="isUpdate" v-model.trim="groupItem.userGroupName"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="简介" prop="desc">
              <el-input :readonly="isUpdate" v-model="groupItem.userGroupDesc"></el-input>
            </el-form-item>
          </el-col>
        </el-col>
        <el-col :span="6" v-if="show">
          <el-form-item label="角色" prop="roles">
            <el-select v-model="groupItem.roles" multiple placeholder="请选择" style="width: 100%">
              <el-option v-for="item in roleList" :key="item.roleId" :label="item.roleName" :value="item.roleId">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6" v-if="show">
          <el-form-item label-width="0px">
            <el-button size="small" @click="chosen('save')" type="primary">
              <i class="fa fa-save"></i> 保存
            </el-button>
            <el-button size="small" @click="chosen('cancel')">
              <i class="fa fa-trash-o"></i> 取消</el-button>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-col :span="6">
            <el-form-item label="检索">
              <el-input placeholder="请输入内容" prefix-icon="el-icon-search" style="width: 100%" v-model="names">
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label-width="0px">
              <el-button size="small" @click="getConditions" type="info" plain>
                查询
              </el-button>
              <el-button v-if="roleIdList.includes(78)" size="small" @click="openModal('users')" type="info" plain>
                添加用户
              </el-button>
            </el-form-item>
          </el-col>
        </el-col>
      </el-form>
      <el-table ref="table" :data="tableData" style="width: 100%" :max-height="client.height-102-50-20-80-32-70" highlight-current-row
        @cell-mouse-enter="handleCurrentChange" @cell-mouse-leave="removeCurrentChange">
        <el-table-column label="序号" prop="fNum" show-overflow-tooltip>
        </el-table-column>
        <el-table-column label="用户名" prop="userName" show-overflow-tooltip>
        </el-table-column>
        <el-table-column label="职位" prop="position" show-overflow-tooltip>
        </el-table-column>
        <el-table-column label="手机号码" prop="mobile" show-overflow-tooltip>
        </el-table-column>
        <el-table-column label="工作电话" prop="tel" show-overflow-tooltip>
        </el-table-column>
        <el-table-column label="电子邮件" prop="email" show-overflow-tooltip>
        </el-table-column>
        <!-- <el-table-column show-overflow-tooltip label="状态" prop="status">
          <template slot-scope="scope">
            {{scope.row.status===2?'在职':'休假'}}
          </template>
        </el-table-column> -->
        <el-table-column min-width="90">
          <template slot-scope="scope">
            <div class="table_operate" v-if="currentRow === scope.row.userId">
              <el-button class="table_operate_btn table_delete" @click.native.prevent="deleteRow(scope.row.userId)" type="text" size="small">
                <i class="fa fa-trash-o"></i> 移除
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <div class="block page_detail">
        <el-pagination @current-change="handlePageCurrentChange" :current-page.sync="pageCurrent" :page-size="pageSize" layout="prev, pager, next, jumper"
          :total="total">
        </el-pagination>
      </div>
    </el-main>
    <AddModal :addModal="addModal" :options="options" :operateType="operateType" :currentId="operateType === 'userGroup'?'':(groupItem.userGroupId+'')"
      @closeModal="closeModal" @operateFinish="operateFinish" />
  </el-container>
</template>

<script>
  import side_tree from "../aside";
  import AddModal from "./addModal.vue";
  import {
    userGroupManagement
  } from "../../../service/service_zbw";
  import {
    dataSort,
    formCheck,
    deepClone
  } from "../../../lib/utils";
  import {
    mapState
  } from "vuex";
  export default {
    computed: {
      ...mapState({
        client: state => state.client,
        roleList: state => state.roleList,
        roleIdList: state => state.roleIdList
      })
    },
    components: {
      side_tree,
      AddModal
    },
    data() {
      return {
        //表格数据
        tableData: [],
        //左侧树数据
        treeData: [],
        //用户列表
        options: [{
            value: "选项1",
            label: "黄金糕"
          },
          {
            value: "选项2",
            label: "双皮奶"
          },
          {
            value: "选项3",
            label: "蚵仔煎"
          },
          {
            value: "选项4",
            label: "龙须面"
          },
          {
            value: "选项5",
            label: "北京烤鸭"
          }
        ],
        copyGroupItem: "",
        //左侧选中节点数据
        groupItem: {
          userGroupId: 0,
          userGroupName: "",
          userGroupDesc: "",
          roles: []
        },
        groupRules: {
          userGroupName: [{
              required: true,
              message: "请输入用户组名称",
              trigger: "blur"
            },
            {
              min: 1,
              max: 10,
              message: "长度不超过10个字符",
              trigger: "blur"
            }
          ]
        },
        //检索栏内的名称
        names: "",
        //模态框开启关闭状态
        addModal: false,
        currentRow: "",
        total: 0,
        pageCurrent: 1,
        pageSize: 50,
        isUpdate: true,
        show: false,
        operateType: "userGroup"
      };
    },
    methods: {
      init() {
        this.getUserGroup(true);
      },
      /**
       * 打开新增模态框
       */
      openModal(val) {
        this.isUpdate = true;
        this.show = false;
        this.operateType = val;
        this.addModal = true;
      },
      /**
       * 获取用户组列表
       */
      async getUserGroup(status, val) {
        let res = await userGroupManagement.getUserGroup();
        if (res.success) {
          if (res.obj.length <= 0) {
            this.groupItem = {
              userGroupId: 0,
              userGroupName: "",
              userGroupDesc: "",
              roles: []
            };
            this.groupItem.roles = [];
            this.treeData = [];
            return;
          }
          if (status) {
            if (res.obj.length > 0) {
              this.groupItem = deepClone(res.obj[0]);
              this.groupItem.roles = this.formatRoleData(this.groupItem.roles);
            }
          } else if (val) {
            for (let i = 0; i < res.obj.length; i++) {
              if (res.obj[i].userGroupId === val) {
                this.groupItem = deepClone(res.obj[i]);
              }
            }
          }
          console.log('this.groupItem=====================',this.groupItem)
          this.treeData = res.obj;
          for (let i of this.treeData) {
            i.id = i.userGroupId;
          }
          console.log('this.treeData=====================',this.treeData)
        } else {
          this.treeData = [];
          this.$message({
            type: "error",
            message: res.msg
          });
        }
      },
      /**
       * 整理角色数组
       */
      formatRoleData(val) {
        let arr = [];
        for (let i of val) {
          console.log("typeof i-----------", typeof i);
          console.log("typeof i !== 'Number'", typeof i !== "Number");
          if (typeof i !== "Number") {
            return;
          }
          arr.push(i.roleId);
        }
        return arr;
      },
      /**
       * 整理查询条件
       */
      getConditions() {
        let param = {
          pageCurrent: this.pageCurrent,
          pageSize: this.pageSize,
          userGroupId: this.groupItem.userGroupId,
          userNames: this.names
        };
        this.getGroupUsers(param);
      },
      /**
       * 获取表格数据
       */
      async getGroupUsers(param) {
        let res = await userGroupManagement.getGroupUsers(param);
        if (res.success) {
          this.total = res.obj.itemTotal;
          this.tableData = dataSort(res.obj.items, this.pageCurrent);
        } else {
          this.total = 0;
          this.tableData = [];
          this.$message({
            message: res.msg,
            type: "error"
          });
        }
      },
      /**
       * 删除人员
       */
      async deleteRow(userId) {
        this.isUpdate = true;
        this.show = false;
        let param = {
          userGroupId: this.groupItem.userGroupId,
          userId: userId
        };
        let res = await userGroupManagement.delGroupUser(param);
        if (res.success) {
          this.getConditions();
          this.$message({
            message: res.msg,
            type: "success"
          });
        } else {
          this.$message({
            message: res.msg,
            type: "error"
          });
        }
      },
      /**
       * hover表格某一行获取id
       */
      handleCurrentChange(val) {
        //当删除当前行时,val值不存在
        try {
          this.currentRow = val.userId;
        } catch (error) {
          this.currentRow = "";
        }
      },
      /**
       * 当前选中行改变
       */
      removeCurrentChange() {
        this.currentRow = "";
      },
      /**
       * 分页改变
       */
      handlePageCurrentChange(val) {
        this.pageCurrent = val;
        this.getConditions();
      },
      /**
       * 编辑，保存，修改
       */
      async chosen(val, id) {
        if (val === "edit") {
          this.copyGroupItem = deepClone(this.groupItem);
          this.isUpdate = !this.isUpdate;
          this.show = !this.show;
        } else if (val === "save") {
          let flag = formCheck(this, "groupItem");
          if (!flag) {
            return;
          }
          let param = {
            roleIds: this.groupItem.roles,
            userGroupDesc: this.groupItem.userGroupDesc,
            userGroupId: this.groupItem.userGroupId,
            userGroupName: this.groupItem.userGroupName
          };
          let res = await userGroupManagement.updateGroup(param);
          if (res.success) {
            this.getUserGroup(false);
            this.isUpdate = !this.isUpdate;
            this.show = !this.show;
            this.$message({
              message: res.msg,
              type: "success"
            });
          } else {
            this.$message({
              message: res.msg,
              type: "error"
            });
          }
        } else if (val === "cancel") {
          this.handleReset("groupItem");
          this.groupItem = deepClone(this.copyGroupItem);
          this.isUpdate = !this.isUpdate;
          this.show = !this.show;
        }
      },
      /**
       * 删除用户组
       */
      del() {
        this.isUpdate = true;
        this.show = false;
        this.$confirm(
            "您确定要删除用户组“" + this.groupItem.userGroupName + "”吗？",
            "询问", {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning",
              center: true
            }
          )
          .then(() => {
            this.delGroup();
          })
          .catch(() => {
            //TODO
          });
      },
      async delGroup() {
        let param = this.groupItem.userGroupId;
        let res = await userGroupManagement.delGroup(param);
        if (res.success) {
          this.getUserGroup(true);
          this.$message({
            message: res.msg,
            type: "success"
          });
        } else {
          this.$message({
            message: res.msg,
            type: "error"
          });
        }
      },
      /**
       * 操作完成
       */
      operateFinish(val) {
        console.log(val);
        if (val.type === "userGroup") {
          //   this.groupItem = deepClone(val.obj);
          //   this.groupItem = val.obj;
          //   this.groupItem.roles = deepClone(this.groupItem.roleIds);
          this.getUserGroup(false, val.userGroupId);
        } else {
          this.getConditions();
        }
        console.log("this.groupItem--------------------------", this.groupItem);
      },
      /**
       * 左侧树选中
       */
      childtofather(val) {
        this.groupItem = deepClone(val);
        if (!val.userGroupDesc) {
          this.groupItem.userGroupDesc = "";
        }
        console.log("this.groupItem--------------------------", this.groupItem);
        this.groupItem.roles = this.formatRoleData(this.groupItem.roles);
      },
      /**
       * 关闭模态框
       */
      closeModal(val) {
        this.addModal = val;
      },
      /**
       * 清空表单
       */
      handleReset(name) {
        this.$refs[name].resetFields();
      }
    },
    watch: {
      "groupItem.userGroupId" (newval) {
        this.isUpdate = true;
        this.show = false;
        if (newval) {
          this.getConditions();
        }
      }
    },
    mounted() {
      this.init();

      console.log(this.roleList);
    }
  };

</script>

<style scoped>
  h1 {
    width: 25%;
    font-weight: bold;
    color: #666666;
    font-size: 18px;
  }

  .table_show,
  .table_show:link,
  .table_show:visited,
  .table_show:hover,
  .table_show:active {
    background: #535953;
    color: #fff;
  }

  .table_delete,
  .table_delete:link,
  .table_delete:visited,
  .table_delete:hover,
  .table_delete:active {
    background: #d9524e;
    color: #fff;
  }

  .table_ok {
    width: 80px;
    background: #409eff;
    color: #fff;
    border-color: #409eff;
  }

  .table_cancel {
    width: 80px;
    background: #d8d8d8;
    color: #666;
    border: 1px solid #999;
  }

</style>

